package com.liugh.controller.zhongche;

import cn.hutool.core.text.StrSpliter;
import cn.hutool.core.util.StrUtil;
import com.liugh.base.PublicResultConstant;
import com.liugh.config.ResponseModel;
import com.liugh.controller.BaseRestController;
import com.liugh.service.zhongche.ISearchService;
import com.liugh.util.FileUpload;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.csource.common.MyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@Api(description = "文件操作模块")
@RequestMapping("/file")
public class UploadController extends BaseRestController {
    private static Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    private ISearchService iSearchService;

    @ApiOperation(value = "文件上传")
//    @Log(action = "fileUpload",modelName = "File",description = "文件上传接口")
    @PostMapping("/upload")
    public ResponseModel<String> singleFileUpload(@RequestParam("file") MultipartFile file) throws IOException, MyException {
        String path = "";
        if (! file.isEmpty()) {
            try {
                path = FileUpload.saveFile(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (StrUtil.isEmpty(path)) {
            throw new MyException(PublicResultConstant.UPLOAD_FILE_FAIL);
        }
        logger.info("远程文件存储位置：" + path);
        List<String> strings = StrSpliter.split(path,":8888",0,true,true);

        //存储原始文件名
        if (! iSearchService.addOriginName(strings.get(1),file.getOriginalFilename())) {
            logger.error("存储文件名出错：远程文件名：{},原始文件名:{}",strings.get(1),file.getOriginalFilename());
        }
        return fillSuccessData(path);
    }
}
